<?php

namespace app\api\controller;

/**
 * @author Sunny
 * @date 2023/5/31
 * @time 14:06 下午
 * @focus love & life
 */

use app\auto\model\Method;
use hg\apidoc\annotation as Apidoc;
use hg\apidoc\annotation\Param;
use think\db\Raw;
use think\Exception;
use think\facade\Db;
use think\response\Json;
/**
 * 网站锚链接
 *
 * api-SiteLink
 *
 * @Apidoc\Title("网站锚链接")
 * @Apidoc\Group("api")
 */
class SiteLink extends Auth
{
    /**
     * list
     * @Apidoc\Title("链接列表")
     */
    public function list()
    {
        $site_id=input("site_id",0,"intval");
        $where[] = ['member_id', '=', $this->request->uid];
        $where[] = ['site_id', '=',$site_id];
        $res = \app\common\model\SiteLink::order("id asc")
            ->where($where)->select();
        $res = $res->toArray();

        return success('ok', $res);
    }   


    /**
     * @Apidoc\Title("新增or更新（是否有id）")
     * @Apidoc\Method("post")
     */
    public function add()
    {
        $data = request()->post(['id','site_id','name', 'url']);
        validate([
            'name|链接名称' => 'require',
            'url|链接地址' => 'url',
            'site_id|站点id' => 'require',
        ])->check($data);
        $data['member_id']=$this->request->uid;
        $id = 0;
        if($data['id']) {
            \app\common\model\SiteLink::update($data);
            $id = $data['id'];
        }else{
            $site = \app\common\model\SiteLink::create($data);
            $id = $site->id;
        }
        return success('', ['id' => $id]);
    }




    /**
     * delete
     * @Apidoc\Method("post")
     * @Param("id", type="int", desc="id",require=true)
     * @Apidoc\Title("删除")
     */
    public function delete()
    {
        $id = input('id');
        $siteLink = \app\common\model\SiteLink::find($id);
        if($siteLink['member_id'] != $this->request->uid) {
            return error('非法请求');
        }
        \app\common\model\SiteLink::destroy($id);
        return success();
    }    
}